/**
 * Packages the parameters into a delta object for use with submitDelta.
 * @param {!(string|Object.<!string, !string>)}  Either an object denoting
 *     the desired key value pair(s), or a single string key.
 * @param {!string=} opt_value If keyOrState is a string, the associated
 *     string value.
 */
var prepareForSave = function(keyOrState, opt_value) {
  var state = null;
  if (typeof keyOrState === 'string') {
    state = {};
    state[keyOrState] = opt_value;
  } else if (typeof keyOrState === 'object' && null !== keyOrState) {
    // Ensure that no prototype-level properties are hitching a ride.
    state = {};
    for (var key in keyOrState) {
      if (keyOrState.hasOwnProperty(key)) {
        state[key] = keyOrState[key];
      }
    }
  } else {
    throw 'Unexpected argument.';
  }
  return state;
};

/**
 * A global place for keeping a list of hangout paticipants
 */
var participants_ = [];

/**
 * A place to hold the user profiles
 **/
var profiles_ = {};

/**
 * Places lived,
 * String: number
 */
var places_ = {};

/**
 * Schools
 * String: number
 */
var schools_ = {};

/**
 * Employers
 * String: number
 */
var employers_ = {};

/**
 * Occupations
 * String: number
 */
var occupations_ = {};

/**
 * When hangout API is ready, try load G+ api
 */
var hangoutInit = function() {
  gapi.client.load('plus', 'v1', function() {
      console.log('G+ api loaded.');
      appInit(); });
  gapi.client.setApiKey('AIzaSyC428LK6PpW8x8o4j3x5aqyD1tzzKDmui8');
};

/**
 * When G+ api is loaded, really started the app init
 */
var appInit = function() {
  // prepare for the display div
  $('body').append('<div id="fillme"/>');

  testGetPeople();
  //Set up state change listener
  gapi.hangout.onParticipantsChanged.add(
      function(participantsChangedEvent) {
        updateParticipants(participantsChangedEvent);
    });

  updateAllParticipants();
};

var updateAllParticipants = function() {
  participants_ = gapi.hangout.getParticipants();
  getProfiles();
  var delayRender = setTimeout("render()", 2000);
};

var updateParticipants = function(participantChangedEvent) {
  console.log('participants changed!');
  participants_ = participantChangedEvent.participants;
  getProfiles();
  var delayRender = setTimeout("render()", 2000);
};

var getProfiles = function() {
  // clear the profiles;
  profiles_ = {};
  for(i = 0; i < participants_.length; ++i) {
    var request = gapi.client.plus.people.get({'userId': participants_[i].person.id});
    request.execute(function(resp) {
        saveUserProfile(resp)
            });
  }
};

var saveUserProfile = function(resp) {
  // resp is a people resource object
  id = resp.id;
  profiles_[id] = resp;
};

var render = function() {
  collectFacts();

  var fillmeDiv = $('#fillme');
  fillmeDiv.empty();
  // Places div
  var placesDiv = $('<div id="places" class="places"></div>');
  var worksDiv = $('<div id="works" class="works"></div>');
  var schoolsDiv = $('<div id="schools" class="shools"></div>');
  fillmeDiv.append(placesDiv);
  fillmeDiv.append(worksDiv);
  fillmeDiv.append(schoolsDiv);

  var ulDiv = $('<ul></ul>');
  placesDiv.append(ulDiv);
  for(var place in places_) {
    ulDiv.append($('<li>' + place + ' : ' + places_[place] + '</li>'));
  }

  // $('#fillme').empty();
  // for(i = 0; i < participants_.length; ++i) {
  //   $('#fillme').append(
  //       '<li>' + participants_[i].person.displayName + '</li>');
  // }
};

/**
 * Parse the participants inform and call into G+ api
 * to get the inform.
 * too bad there is no batch api to get user info
 */
var collectFacts = function() {
  schools_ = {};
  employers_ = {};
  places_ = {};
  occupations_ = {};

  // Iterate the profiles, rely one the fact JS is single threaded
  for (var id in profiles_) {
    var orgName = '';
    var palces = '';
    // Parse orgnizations
    if (profiles_[id].organizations != undefined) {
      var orgLength = profiles_[id].organizations.length;
      for (var i = 0; i < orgLenght; ++i) {
        var org = profiles_[id].organizations[i];
        orgName = org.Name;
        if (orgName) {
          if (org.type == 'school'){
            setOrAddOne(schools_, orgName);
          }
          else if (org.type == 'work') {
            setOrAddOne(employers_, orgName);
            if (org.title) {
              setOrAddOne(occupations_, org.title);
            }
          }
        }
      }
    }

    // Parse places
    if (profiles_[id].placesLived != undefined){
      var placesLength = profiles_[id].placesLived.length;
      for (var i = 0; i < placesLength; ++i) {
        setOrAddOne(places_, profiles_[id].placesLived[i].value);
      }
    }
  }
};

var setOrAddOne = function(hashMap, key) {
  if (hashMap[key] == undefined){
    hashMap[key] = 1;
  }
  else {
    hashMap[key] += 1;
  }
};

var testGetPeople = function() {
  //var request = gapi.client.plus.people.get({'userId': '113220668349795241439'});
  var request = gapi.client.plus.people.get({'userId': '103679899283654887386'});
  request.execute(function(resp) { console.log(resp); });
};

var updateLocalDataState = function(state, metadata){
  image_url = state['shared-image'];
};

var updateLocalDataStateAndRender = function(state, metadata){
  image_url = state['shared-image'];
  render();
};

// register start point
gapi.hangout.onApiReady.add(hangoutInit);